//!@Author: DengLibin
//!@Date: Create in 2025-05-08 12:06:39
//!@Description:
//!

use sqlx::{mysql::MySqlArguments, MySql, Pool, Transaction};

use crate::{
    entity::file_path::FilePath,
    sys::global::{to_global_result, GlobalResult},
};

///@Author: DengLibin
///@Date: Create in 2025-05-08 12:08:56
///@Description: 查询
pub async fn limit_by_id(
    start_id: i64,
    limit: u32,
    table_name: &str,
    pool: &Pool<MySql>,
) -> GlobalResult<Vec<FilePath>> {
    let sql = format!("SELECT id, path, dic_id  FROM {} where id > ? order by id limit ?",  table_name);
    let result = sqlx::query_as::<MySql, FilePath>(&sql)
        .bind(start_id)
        .bind(limit)
        .fetch_all(pool)
        .await?;
    Result::Ok(result)
}

pub async fn update_dic_id(
    id: i64,
    dic_id: &str,
    table_name: &str,
    pool: &Pool<MySql>,
) -> GlobalResult<()> {
    let sql = format!( "update {} set dic_id=? where id=?", table_name);

    let mut tx: Transaction<'_, MySql> = to_global_result(pool.begin().await)?;
    // 执行 SQL 查询
    // 构建查询并绑定参数id
    let mut query: sqlx::query::Query<MySql, MySqlArguments> = sqlx::query::<MySql>(&sql);

    query = query.bind(dic_id).bind(id);

    let r = query.execute(&mut *tx).await;
    if let Err(err) = r {
        // 回滚事务
        to_global_result(tx.rollback().await)?;
        return Err(anyhow::anyhow!(err.to_string()));
    } else {
        //提交
        to_global_result(tx.commit().await)
    }
}
